package com.kajespero.android.mapping.process;

import java.io.Serializable;
import java.lang.reflect.Field;
import java.util.Collection;

import android.view.View;
import android.widget.TextView;

import com.kajespero.android.mapping.annotation.AndroidComponent;
import com.kajespero.android.mapping.annotation.AndroidRoot;
import com.kajespero.json.helper.ClassHelper;

public class AndroidAnnotationProcess {
	
	public static <E extends Serializable> void process(View view, E to){
		AndroidRoot androidRoot = ClassHelper.getDeclaredAnnotation(to.getClass(), AndroidRoot.class);
		View viewRoot = (View) view.getParent();
		View component = viewRoot.findViewById(androidRoot.id());
		processField(component, to);
	}
	
	private static <E extends Serializable> void processField(View root , E to){
		Collection<Field> fields = ClassHelper.getField(to.getClass(), AndroidComponent.class);
		for(Field field : fields){
			AndroidComponent androidComponent = field.getAnnotation(AndroidComponent.class);
			View component =  root.findViewById(androidComponent.id());
			setInstance(field, to, component, androidComponent.componentClass());
		}
	}
	
	private static <E, T> void setInstance(Field field, E instance, View component, Class<T> clazz){
		if(component != null){
			if(clazz.getName().equals(TextView.class.getName())){
				TextView view = (TextView)component;
				String value = ClassHelper.getField(field, instance);
				if(view.getText() != null){
					value = view.getText().toString();
				}
				ClassHelper.setField(field, instance, value);
			}
		}
	}
}
